//
//  TabbarHeaderView.swift
//  Exchange
//
//  Created by rui on 2018/4/25.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

enum TabberHeaderType {
    case normal
    case underLine
    case underLine2
    case underLine3
    case redDot
}

protocol TabbarHeaderViewDelegate: class {
    func tabbarHeader(headerView: TabbarHeaderView,selectIndex: Int)
}

let kRedW: CGFloat = 8

class TabbarHeaderView: UIView {
    
    private var titles: [String]
    weak var delegate: TabbarHeaderViewDelegate?
    private var selectIndex: Int = -1
    private var buttonArray = [UIButton]()
    var type: TabberHeaderType = .normal
    
    private lazy var redDotViews: [UIView] = []

    private lazy var scroll: UIScrollView = {
        let scroll = UIScrollView()
        scroll.showsVerticalScrollIndicator = false
        scroll.showsHorizontalScrollIndicator = false
        scroll.bounces = false
        scroll.themeBackground = ThemeManager.ThemeColorKeys.background
        return scroll
    }()
    
    private lazy var indicatorView: UIView = {
        let indicator = UIView()
        if self.type == .underLine || self.type == .underLine2 || self.type == .redDot || self.type == .underLine3 {
            
        }else {
            indicator.layer.cornerRadius = 11
            indicator.layer.masksToBounds = true
        }
        indicator.backgroundColor = kThemeColor
        return indicator
    }()
    
    private var line: UIView = {
        let view = UIView()
        view.themeBackground = ThemeManager.ThemeColorKeys.separator
        return view
    }()
    
    convenience init(titles: [String],type: TabberHeaderType = .normal) {
        self.init(frame: CGRect.zero, titles: titles, type: type)
    }
    init(frame: CGRect,titles: [String],type: TabberHeaderType = .normal) {
        self.titles = titles
        self.type = type
        super.init(frame: frame)
        initUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func initUI() {
        addSubview(scroll)
        scroll.addSubview(indicatorView)
        if type == .underLine2 {
            
        }else {
            scroll.addSubview(line)
        }
        var index = 0
        for title in titles {
            let btn = UIButton(type: .custom)
            btn.autoresizingMask = .flexibleHeight
            btn.setTitle(title, for: .normal)
            btn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text2, for: .normal)
            if self.type == .normal {
                btn.setTitleColor(kBackgroundColor, for: .selected)
            }else if self.type == .underLine || self.type == .underLine2 || self.type == .underLine3 {
                btn.setTitleColor(kThemeColor, for: .selected)
            }else if self.type == .redDot {
                let view = UIView()
                view.layer.cornerRadius = kRedW * 0.5
                view.layer.masksToBounds = true
                view.backgroundColor = UIColor.red
                view.isHidden = true
                scroll.addSubview(view)
                self.redDotViews.append(view)
                btn.setTitleColor(kThemeColor, for: .selected)
            }
            btn.addTarget(self, action: #selector(btnSelect(btn:)), for: .touchUpInside)
            btn.tag = index
            btn.backgroundColor = UIColor.clear
            index += 1
            btn.titleLabel?.textAlignment = .center
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            buttonArray.append(btn)
            scroll.addSubview(btn)
        }
        layout()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        layout()
    }
    
    func layout() {
        if self.type == .underLine3 {
            scroll.frame = CGRect(x: 80, y: 0, width: bounds.size.width - 160, height: bounds.size.height)
        }else {
            scroll.frame = bounds
        }
        
        let count = self.buttonArray.count
        let item_w = scroll.frame.size.width / CGFloat(count)
        var tempBtn = UIButton()
        if type == .normal {
            for btn in buttonArray {
                btn.sizeToFit()
                //            let btn_w = btn.frame.size.width > item_w ? btn.frame.size.width + 20 : item_w
                let btn_w =  btn.frame.size.width + 40
                btn.frame = CGRect(x: tempBtn.right, y: 5, width: btn_w, height: self.frame.size.height - 10)
                tempBtn = btn
            }
            
            indicatorView.frame = CGRect(x: 0, y: 9, width: item_w * 0.6, height: 22)
        }else if type == .underLine || type == .underLine2 || type == .underLine3 {
            for btn in buttonArray {
                btn.sizeToFit()
                let btn_w = btn.frame.size.width > item_w ? btn.frame.size.width + 20 : item_w
                btn.frame = CGRect(x: tempBtn.right, y: 5, width: btn_w, height: self.frame.size.height - 10)
                tempBtn = btn
            }
            indicatorView.frame = CGRect(x: 0, y: self.height - 2.5, width: item_w * 0.6, height: 2)
        }else if type == .redDot {
            var btn: UIButton
            for i in 0..<buttonArray.count {
                btn = buttonArray[i]
                let redView = redDotViews[i]
                
                btn.sizeToFit()
                let btn_w = btn.frame.size.width > item_w ? btn.frame.size.width + 20 : item_w
                btn.frame = CGRect(x: tempBtn.right, y: 5, width: btn_w, height: self.frame.size.height - 10)
                redView.frame = CGRect(x: btn.right - 13, y: 10, width: kRedW, height: kRedW)
                tempBtn = btn
            }
            indicatorView.frame = CGRect(x: 0, y: self.height - 2.5, width: item_w * 0.6, height: 2)
        }
        scroll.contentSize = CGSize(width: tempBtn.right, height: self.frame.size.height)
        if type == .underLine3 {
            if tempBtn.right >= self.width {
                scroll.frame = CGRect(x: 0, y: 0, width: self.width, height: bounds.size.height)
            }else {
                let x = (self.width - tempBtn.right) * 0.5
                scroll.frame = CGRect(x: x, y: 0, width: self.width - 2 * x, height: bounds.size.height)
            }
        }
        scroll.contentInset = UIEdgeInsets.zero
        if type == .underLine2 || type == .redDot {
            
        }else {
            line.frame = CGRect(x: 16, y: self.height - 0.5, width: kSCREEN_WIDTH - 32, height: 0.5)
        }
        fouce(selectIndex: selectIndex)
        layoutIndicator()
    }
    
    func fouce(selectIndex index: Int,animated: Bool = false) {
        var nowIndex = index
        if nowIndex == -1 {nowIndex = 0}
//        if nowIndex == self.selectIndex {return}
        self.selectIndex = nowIndex
        for btn in buttonArray {
            btn.isSelected = btn.tag == index
        }
        layoutIndicator(animated: animated)
    }
    
    private func layoutIndicator(animated: Bool = false) {
        if buttonArray.count <= selectIndex {
            return
        }
        let btn = buttonArray[selectIndex]
        let animations = {
            var w: CGFloat
            if self.type == .underLine || self.type == .underLine2 || self.type == .redDot || self.type == .underLine3 {
                w = (btn.titleLabel?.text?.ch_sizeWithConstrained(btn.titleLabel!.font).width)! * 0.6
            }else {
                w = btn.width - 20
            }
            self.indicatorView.width = w
            self.indicatorView.centerX = btn.centerX
            let postionX = self.indicatorView.centerX
            let sw: CGFloat = self.scroll.frame.size.width
            let delatX = self.indicatorView.centerX - sw * 0.5
            if delatX > 0 {
                if postionX < self.scroll.contentSize.width - sw * 0.5 {
                    self.scroll.contentOffset = CGPoint(x: delatX, y: self.scroll.contentOffset.y)
                }else {
                    self.scroll.contentOffset = CGPoint(x: self.scroll.contentSize.width - sw, y: self.scroll.contentOffset.y)
                }
            }else {
                self.scroll.contentOffset = CGPoint(x: 0, y: self.scroll.contentOffset.y)
            }
        }
        
        if animated {
            UIView.animate(withDuration: 0.25) {
                animations()
            }
        }else {
            animations()
        }
    }
    
    ///设置红点位置
    func setRedViewsIsHidden(postions: [Bool]) {
        if self.redDotViews.count <= 0 || postions.count != self.redDotViews.count {
            return
        }
        for i in 0..<self.redDotViews.count {
            let view = self.redDotViews[i]
            let isHidden = postions[i]
            view.isHidden = isHidden
        }
    }
    
    @objc func btnSelect(btn: UIButton){
        self.delegate?.tabbarHeader(headerView: self, selectIndex: btn.tag)
        fouce(selectIndex: btn.tag, animated: true)
    }
}
